#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from utility import tools
from event import event_type
from command import command
import logging

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class ArchivesAddAPI(Resource):
    """
    新增产妇建档基本信息
    :request: post
    :param jdSfby: 是否本院建档
    :param jdDw: 建档单位
    :param jdDate: 外院建档时间
    :param jdByfmYy: 本院分娩意愿
    :param jdQd: 建档渠道
    :param jdYsCode: 建档医生编码
    :param jdYsxm：建档医生姓名
    :param fq: 父亲基本信息
            {   
                "fqXm": 父亲姓名
                "fqZjlx": 证件类型
                "fqZjhm": 证件号码
                "fqCsrq": 出生日期
                "fqSjhm": 手机号码
                "fqMz": 民族
                "fqZy": 职业
            } 
    :param mq: 母亲基础信息
            {
                "mqXm": 母亲姓名
                "mqIdType": 证件类型
                "mqSfz": 身份证号
                "mqCsrq": 出生日期
                "mqMz": 民族
                "mqXx": 血型
                "mqRhyx": RH阴性
                "mqZy": 职业
                "mqSjhm": 手机号码
                "mqHyzk": 婚姻状况
                "mqHjlx": 户籍类型
                "mqHj": 户籍省市区
                "mqJt": 家庭省市区
                "mqCz": 常住省市区
                "mqHjAddress": 户籍详细地址
                "mqJtAddress": 家庭详细地址
                "mqCzAddress": 常住详细地址
                "mqQmjkjc": 全民健康体检
                "mqJbggws": 基本公共卫生
                "mqLdrk": 是否流动人口
                "mqDjny": 定居年月
                "mqMzh": 门诊号
            
            }       
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['jdSfby','mq','fq','jdQd','jdDw','jdDate','jdByfmYy','jdYsCode']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            data_={
                'mq_xm': params.get('mq')['mqXm'],
                'mq_id_type': params.get('mq')['mqIdType'],
                'mq_sfz': params.get('mq')['mqSfz'],
                'mq_age': tools.calculate_age_by_card(params.get('mq')['mqSfz']),
                # 'mq_csrq': params.get('mq')['mqCsrq'],
                'mq_mz': params.get('mq')['mqMz'],
                'mq_xx': params.get('mq')['mqXx'],
                'mq_rhyx': params.get('mq')['mqRhyx'],
                'mq_zy': params.get('mq')['mqZy'],
                'mq_sjhm': params.get('mq')['mqSjhm'],
                'mq_hyzk': params.get('mq')['mqHyzk'],
                'mq_hjlx': params.get('mq')['mqHjlx'],
                'mq_hj_province': params.get('mq')['mqHj'][0] if len(params.get('mq')['mqHj'])>0 else '',
                'mq_hj_city': params.get('mq')['mqHj'][1] if len(params.get('mq')['mqHj'])>1 else '',
                'mq_hj_county': params.get('mq')['mqHj'][2] if len(params.get('mq')['mqHj'])>2 else '',
                'mq_hj_town': params.get('mq')['mqHj'][3] if len(params.get('mq')['mqHj'])>3 else '',
                'mq_hj_village': params.get('mq')['mqHj'][4] if len(params.get('mq')['mqHj'])>4 else '',
                'mq_hj_address': params.get('mq')['mqHjAddress'],
                'mq_jt_province': params.get('mq')['mqJt'][0] if len(params.get('mq')['mqJt'])>0 else '',
                'mq_jt_city': params.get('mq')['mqJt'][1] if len(params.get('mq')['mqJt'])>1 else '',
                'mq_jt_county': params.get('mq')['mqJt'][2] if len(params.get('mq')['mqJt'])>2 else '',
                'mq_jt_town': params.get('mq')['mqJt'][3] if len(params.get('mq')['mqJt'])>3 else '',
                'mq_jt_village': params.get('mq')['mqJt'][4] if len(params.get('mq')['mqJt'])>4 else '',
                'mq_jt_address': params.get('mq')['mqJtAddress'],
                'mq_cz_province': params.get('mq')['mqCz'][0] if len(params.get('mq')['mqCz'])>0 else '',
                'mq_cz_city': params.get('mq')['mqCz'][1] if len(params.get('mq')['mqCz'])>1 else '',
                'mq_cz_county': params.get('mq')['mqCz'][2] if len(params.get('mq')['mqCz'])>2 else '',
                'mq_cz_town': params.get('mq')['mqCz'][3] if len(params.get('mq')['mqCz'])>3 else '',
                'mq_cz_village': params.get('mq')['mqCz'][4] if len(params.get('mq')['mqCz'])>4 else '',
                'mq_cz_address': params.get('mq')['mqCzAddress'],
                'mq_qmjkjc': params.get('mq')['mqQmjkjc'],
                'mq_jbggws': params.get('mq')['mqJbggws'],
                'mq_ldrk': params.get('mq')['mqLdrk'],
                'mq_djny': params.get('mq')['mqDjny'],
                'fq_xm': params.get('fq')['fqXm'],
                'fq_zjlx': params.get('fq')['fqZjlx'],
                'fq_zjhm': params.get('fq')['fqZjhm'],
                # 'fq_csrq': params.get('fq')['fqCsrq'],
                'fq_sjhm': params.get('fq')['fqSjhm'],
                'fq_mz': params.get('fq')['fqMz'],
                'fq_zy': params.get('fq')['fqZy'],
                'jd_sfby': params.get('jdSfby'),
                'jd_dw': params.get('jdDw'),
                # 'jd_date': params.get('jdDate'),
                'jd_yy': params.get('jdByfmYy'),
                'jd_qd': params.get('jdQd'),
                'jd_ys': params.get('jdYsCode'), 
                #  'jd_ysxm': params.get('jdYsxm'), 
                'mzh': params.get('mqMzh'),
                'status': '0'
            }
            if params.get('jdDate'):
                data_['jd_date'] = params.get('jdDate')
            if params.get('fq')['fqCsrq']:
                data_['fq_csrq'] = params.get('fq')['fqCsrq']
            if params.get('mq')['mqCsrq']:
                data_['mq_csrq'] = params.get('mq')['mqCsrq']
            data_ = odoo.env['res.archives'].create(data_)
            # 记录操作日志
            create_event = event_type.OperationLogEvent('新增产妇建档基本信息', '档案id:{}'.format(data_))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesUpdateAPI(Resource):
    """
    修改产妇建档基本信息
    :request: put
    :param archivesId: 档案ID
    :param jdSfby：是否本院建档
    :param jdDw：建档单位
    :param jdDate：外院建档时间
    :param jdByfmYy：本院分娩意愿
    :param jdQd：建档渠道
    :param jdYsCode：建档医生编码
    :param jdYsxm：建档医生姓名
    :param fq: 父亲基本信息
            {   
                "fqXm": 父亲姓名
                "fqZjlx": 证件类型
                "fqZjhm": 证件号码
                "fqCsrq": 出生日期
                "fqSjhm": 手机号码
                "fqMz": 民族
                "fqZy": 职业
            } 
    :param mq: 母亲基础信息
            {
                "mqXm": 母亲姓名
                "mqIdType": 证件类型
                "mqSfz": 身份证号
                "mqCsrq": 出生日期
                "mqMz": 民族
                "mqXx": 血型
                "mqRhyx": RH阴性
                "mqZy": 职业
                "mqSjhm": 手机号码
                "mqHyzk": 婚姻状况
                "mqHjlx": 户籍类型
                "mqHj": 户籍省市区
                "mqJt": 家庭省市区
                "mqCz": 常住省市区
                "mqHjAddress": 户籍详细地址
                "mqJtAddress": 家庭详细地址
                "mqCzAddress": 常住详细地址
                "mqQmjkjc": 全民健康体检
                "mqJbggws": 基本公共卫生
                "mqLdrk": 是否流动人口
                "mqDjny": 定居年月
                "mqMzh": 门诊号
            } 
    :returns: json string
    """
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            '''
            req_params = ['archivesId','jdSfby','mq','fq','jdQd','jdDw','jdDate','jdByfmYy','jdYsCode']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            '''   
            query_ = [('id', '=', int(params.get('archivesId')))]
            res_archives_ = odoo.env['res.archives'].search(query_)
            if not res_archives_:
                return jsonify({'code': 40005, 'msg': error_code[40005]})    
            data_={
                #'id': params.get('archivesId'),
                'mq_age': tools.calculate_age_by_card(params.get('mq')['mqSfz']),
                'mq_xm': params.get('mq')['mqXm'],
                'mq_csrq': params.get('mq')['mqCsrq'],
                'mq_mz': params.get('mq')['mqMz'],
                'mq_xx': params.get('mq')['mqXx'],
                'mq_rhyx': params.get('mq')['mqRhyx'],
                'mq_zy': params.get('mq')['mqZy'],
                'mq_sjhm': params.get('mq')['mqSjhm'],
                'mq_hyzk': params.get('mq')['mqHyzk'],
                'mq_hjlx': params.get('mq')['mqHjlx'],
                'mq_hj_province': params.get('mq')['mqHj'][0] if len(params.get('mq')['mqHj'])>0 else '',
                'mq_hj_city': params.get('mq')['mqHj'][1] if len(params.get('mq')['mqHj'])>1 else '',
                'mq_hj_county': params.get('mq')['mqHj'][2] if len(params.get('mq')['mqHj'])>2 else '',
                'mq_hj_town': params.get('mq')['mqHj'][3] if len(params.get('mq')['mqHj'])>3 else '',
                'mq_hj_village': params.get('mq')['mqHj'][4] if len(params.get('mq')['mqHj'])>4 else '',
                'mq_hj_address': params.get('mq')['mqHjAddress'],
                'mq_jt_province': params.get('mq')['mqJt'][0] if len(params.get('mq')['mqJt'])>0 else '',
                'mq_jt_city': params.get('mq')['mqJt'][1] if len(params.get('mq')['mqJt'])>1 else '',
                'mq_jt_county': params.get('mq')['mqJt'][2] if len(params.get('mq')['mqJt'])>2 else '',
                'mq_jt_town': params.get('mq')['mqJt'][3] if len(params.get('mq')['mqJt'])>3 else '',
                'mq_jt_village': params.get('mq')['mqJt'][4] if len(params.get('mq')['mqJt'])>4 else '',
                'mq_jt_address': params.get('mq')['mqJtAddress'],
                'mq_cz_province': params.get('mq')['mqCz'][0] if len(params.get('mq')['mqCz'])>0 else '',
                'mq_cz_city': params.get('mq')['mqCz'][1] if len(params.get('mq')['mqCz'])>1 else '',
                'mq_cz_county': params.get('mq')['mqCz'][2] if len(params.get('mq')['mqCz'])>2 else '',
                'mq_cz_town': params.get('mq')['mqCz'][3] if len(params.get('mq')['mqCz'])>3 else '',
                'mq_cz_village': params.get('mq')['mqCz'][4] if len(params.get('mq')['mqCz'])>4 else '',
                'mq_cz_address': params.get('mq')['mqCzAddress'],
                'mq_qmjkjc': params.get('mq')['mqQmjkjc'],
                'mq_jbggws': params.get('mq')['mqJbggws'],
                'mq_ldrk': params.get('mq')['mqLdrk'],
                'mq_djny': params.get('mq')['mqDjny'],
                'fq_xm': params.get('fq')['fqXm'],
                'fq_zjlx': params.get('fq')['fqZjlx'],
                'fq_zjhm': params.get('fq')['fqZjhm'],
                'fq_csrq': params.get('fq')['fqCsrq'],
                'fq_sjhm': params.get('fq')['fqSjhm'],
                'fq_mz': params.get('fq')['fqMz'],
                'fq_zy': params.get('fq')['fqZy'],
                'jd_sfby': params.get('jdSfby'),
                'jd_dw': params.get('jdDw'),
                'jd_date': params.get('jdDate'),
                'jd_yy': params.get('jdByfmYy'),
                'jd_qd': params.get('jdQd'),
                'jd_ys': params.get('jdYsCode'), 
                # 'jd_ysxm': params.get('jdYsxm'), 
                'mzh': params.get('mqMzh')
            }
            data_ = odoo.env['res.archives'].write(res_archives_,data_)
            print(data_)
            # 记录操作日志
            create_event = event_type.OperationLogEvent('修改产妇建档基本信息', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetWyjdInfoAPI(Resource):
    """
    根据身份证号码查最新外院建档数据
    :request: post
    :param idCardNum：idCardNum
    :param jdDw：建档单位
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['idCardNum','jdDw']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res) 
            cloud_url = odoo.env['ir.config_parameter'].get_param('cloud.ticket.url', False)
            url = '{}{}'.format(cloud_url, '/GetMzData')    
            params = {
                "ticket": tools.get_ticket(odoo, params.get('jdDw')) ,
                "sfzh": params.get('idCardNum'),  # 孕妇身份证号或儿童身份证号
                'type': 'ycfjbxx',
                'startdate': '',  # 开始日期
                'enddate': '' # 结束日期
            }
            req = requests.get(url=url, params=params, headers={'Content-Type': 'application/x-www-form-urlencoded'}, verify=False)
            response = json.loads(req.text)
            data_ = {}
            if response['errorCode'] == '1007':
                cloud_data = response['data']
                data_ = {
                    'mq': {
                        'mqXm': cloud_data['xm'],
                        'mqIdType': '身份证',
                        'mqSfz': cloud_data['sfz'],
                        'mqCsrq': '',
                        'mqMz': cloud_data['mz'],
                        'mqXx': cloud_data['xx'],
                        'mqRhyx': cloud_data['rhxx'],
                        'mqZy': '',
                        'mqSjhm': cloud_data['hjlx'],
                        'mqHyzk': cloud_data['jgbm'],
                        'mqHjlx': cloud_data['xm'],
                        'mqHj': [
                            cloud_data['户籍地址']
                        ],
                        'mqJt': [
                            cloud_data['jtzz']
                        ],
                        'mqCz': [
                            cloud_data['czdlb']
                        ],
                        'mqHjProvince': '',
                        'mqHjCity': '',
                        'mqHjCounty': '',
                        'mqHjTown': '',
                        'mqHjVillage': '',
                        'mqHjAddress': '',
                        'mqJtProvince': '',
                        'mqJtCity': '',
                        'mqJtCounty': '',
                        'mqJtVillage': '',
                        'mqJtTown': '',
                        'mqJtAddress': '',
                        'mqCzProvince': '',
                        'mqCzCity': '',
                        'mqCzCounty': '',
                        'mqCzTown': '',
                        'mqCzVillage': '',
                        'mqCzAddress': '',
                        'mqQmjkjc': False if cloud_data['jbggws'] else cloud_data['jbggws'],
                        'jbggws': cloud_data['jbggws'],
                        'mqLdrk': '',
                        'mqDjny': str(cloud_data['djn'])+str(cloud_data['djy']),
                        'mqMzh': ''
                    },
                    'fq': {
                        'fqXm': cloud_data['ar_xm'],
                        'fqZjlx': '身份证',
                        'fqZjhm': cloud_data['ar_sfz'],
                        'fqCsrq': '',
                        'fqSjhm': cloud_data['ar_lxdh'],
                        'fqMz': cloud_data['ar_mz'],
                        'fqZy': cloud_data['ar_zy']
                    },
                    'jdSfby': '否', 
                    'jdDw': '',
                    'jdDwCode': cloud_data['jddwid'],
                    'jdDate': cloud_data['jdrq'],
                    'jdYsCode': '',
                    'jdYsxm': ''
                }
            query_ = [('mq_sfz', '=',cloud_data['sfz'] ),('status', '=',0)]
            res_archives = odoo.env['res.archives'].search_read(query_)
            if res_archives:
                if cloud_data['jddwid'] == res_archives[0]['hospital_id'][0]:
                    data_['jdSfby']='是'
                    data_['jdDw']=res_archives[0]['hospital_id'][-1]
                else:
                    query_ = [('id', '=',int(cloud_data['jddwid'] ))]
                    hos_ = odoo.env['res.hospital'].search_read(query_)
                    if hos_:
                        data_['jdDw']=hos_[0]['name']    
            return jsonify({'code': 0, 'msg': 'success', 'data': {}})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetArchivesInfoAPI(Resource):
    """
    查询产妇建档基本信息
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  获取孕妇建档信息
            odoo = OdooManager().get_instance()
            query_ = [('id', '=', int(params.get('archivesId')))]
            res_archives = odoo.env['res.archives'].search_read(query_)
            if res_archives:
                res_archive = res_archives[0]
                hj_area_data = tools.parse_area_code(res_archive['mq_hj_province'], res_archive['mq_hj_city'], res_archive['mq_hj_county'], res_archive['mq_hj_town'], res_archive['mq_hj_village'])
                jt_area_data = tools.parse_area_code(res_archive['mq_jt_province'], res_archive['mq_jt_city'], res_archive['mq_jt_county'], res_archive['mq_jt_town'], res_archive['mq_jt_village'])
                cz_area_data = tools.parse_area_code(res_archive['mq_cz_province'], res_archive['mq_cz_city'], res_archive['mq_cz_county'], res_archive['mq_cz_town'], res_archive['mq_cz_village'])
                data_ = {
                    'mq': {
                        'mqXm': res_archive['mq_xm'],
                        'mqIdType': res_archive['mq_id_type'],
                        'mqSfz': res_archive['mq_sfz'],
                        'mqCsrq': res_archive['mq_csrq'],
                        'mqMz': res_archive['mq_mz'],
                        'mqXx': res_archive['mq_xx'],
                        'mqRhyx': res_archive['mq_rhyx'],
                        'mqZy': res_archive['mq_zy'],
                        'mqSjhm': res_archive['mq_sjhm'],
                        'mqHyzk': res_archive['mq_hyzk'],
                        'mqHjlx': res_archive['mq_hjlx'],

                        'mqHj': hj_area_data['code'],
                        'mqJt': jt_area_data['code'],
                        'mqCz': cz_area_data['code'],

                        'mqHjProvince': hj_area_data['province'],
                        'mqHjCity': hj_area_data['city'],
                        'mqHjCounty': hj_area_data['country'],
                        'mqHjTown': hj_area_data['town'],
                        'mqHjVillage': hj_area_data['village'],

                        'mqHjAddress': res_archive['mq_hj_address'],

                        'mqJtProvince': jt_area_data['province'],
                        'mqJtCity': jt_area_data['city'],
                        'mqJtCounty': jt_area_data['country'],
                        'mqJtVillage': jt_area_data['village'],
                        'mqJtTown': jt_area_data['town'],

                        'mqJtAddress': res_archive['mq_jt_address'],

                        'mqCzProvince': cz_area_data['province'],
                        'mqCzCity': cz_area_data['city'],
                        'mqCzCounty': cz_area_data['country'],
                        'mqCzTown': cz_area_data['town'],
                        'mqCzVillage': cz_area_data['village'],

                        'mqCzAddress': res_archive['mq_cz_address'],
                        'mqQmjkjc': res_archive['mq_qmjkjc'],
                        'mqJbggws': res_archive['mq_jbggws'],
                        'mqLdrk': res_archive['mq_ldrk'],
                        'mqDjny': res_archive['mq_djny'],
                        'mqMzh': res_archive['mzh']
                        },
                    'fq': {
                        'fqXm': res_archive['fq_xm'],
                        'fqZjlx': res_archive['fq_zjlx'],
                        'fqZjhm': res_archive['fq_zjhm'],
                        'fqCsrq': res_archive['fq_csrq'],
                        'fqSjhm': res_archive['fq_sjhm'],
                        'fqMz': res_archive['fq_mz'],
                        'fqZy': res_archive['fq_zy']
                    },
                    'jdSfby': res_archive['jd_sfby'],
                    'jdDw': res_archive['jd_dw'][0] if res_archive['jd_dw'] else None,
                    'jdDate': res_archive['jd_date'],
                    'jdByfmYy': res_archive['jd_yy'],
                    'jdQd': res_archive['jd_qd'],
                    'jdYsCode': res_archive['jd_ys'][0] if res_archive['jd_ys'] else '',
                    'jdYsxm': res_archive['jd_ys'][1] if res_archive['jd_ys'] else ''
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

